package com.xlhj.boot.webservice.ws.server.interceptor;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;

import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

/**
 * @Author: caijliu
 * @Date: 06/12/2021 11:51
 * @Description TODO
 * @Vsersion: 0.0.1
 */
@Component
public class WebServiceAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    /**用户名*/
    private static final String USER_NAME = "caijliu";
    /**密码*/
    private static final String USER_PASSWORD = "xlhj.com";
    private static final String NAME_SPACE_URI = "http://service.api.ws.webservice.boot.xlhj.com/";
    /**创建拦截器*/
    private SAAJInInterceptor interceptor = new SAAJInInterceptor();
    private static final Logger logger = LoggerFactory.getLogger(WebServiceAuthInterceptor.class);

    public WebServiceAuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
        //添加拦截
        super.getAfter().add(SAAJInInterceptor.class.getName());
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        //获取指定消息
        SOAPMessage soapMessage = message.getContent(SOAPMessage.class);
        if (null == soapMessage) {
            this.interceptor.handleMessage(message);
            soapMessage = message.getContent(SOAPMessage.class);
        }
        //SOAP头信息
        SOAPHeader header = null;
        try {
            header = soapMessage.getSOAPHeader();
        } catch (SOAPException e) {
            e.printStackTrace();
        }
        if (null == header) {
            throw new Fault(new IllegalAccessException("没有Header信息，无法实现用户认证处理!"));
        }
        //SOAP是基于XML文件结构进行传输的，所以如果要想获取认证信息就必须进行相关的结构约定
        NodeList usernameNodeList = header.getElementsByTagNameNS(NAME_SPACE_URI, "username");
        NodeList passwordNodeList = header.getElementsByTagNameNS(NAME_SPACE_URI, "password");
        if (usernameNodeList.getLength() < 1) {
            throw new Fault(new IllegalAccessException("没有用户信息，无法实现用户认证处理!"));
        }
        if (passwordNodeList.getLength() < 1) {
            throw new Fault(new IllegalAccessException("没有密码信息，无法实现用户认证处理!"));
        }
        String username = usernameNodeList.item(0).getTextContent().trim();
        String password = passwordNodeList.item(0).getTextContent().trim();
        if (USER_NAME.equals(username) && USER_PASSWORD.equals(password)) {
            logger.debug("用户访问认证成功!");
        } else {
            SOAPException soapException = new SOAPException("用户认证失败!");
            logger.debug("用户认证失败!");
            throw new Fault(soapException);
        }
    }
}
